package com.ohs.ohsoa.system.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.ohs.ohsoa.system.dto.InternetHardDrivesFileDto;
import com.ohs.ohsoa.system.dto.InternetHardDrivesFileSubDto;
import com.ohs.ohsoa.system.entity.InternetHardDrivesFile;
import com.ohs.ohsoa.system.mapper.InternetHardDrivesFileMapper;
import com.ohs.ohsoa.system.vo.InternetHardDrivesFileVo;
import com.ohs.ohsoa.utils.bean.requestBean.PageParam;
import com.ohs.ohsoa.utils.exception.BizException;
import org.springframework.beans.BeanUtils;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 网络硬盘文件表接口实现类
 *
 * @author qianjp
 * @since 2021-10-25
 *
 */
@Service
public class InternetHardDrivesFileServiceImpl extends ServiceImpl<InternetHardDrivesFileMapper, InternetHardDrivesFile> implements InternetHardDrivesFileService {

    @Resource
    private InternetHardDrivesFileMapper internetHardDrivesFileMapper;

    @Resource
    private MessageSource messageSource;

    @Override
    public List<InternetHardDrivesFileVo> internetHardDrivesFileSelectList(PageParam<InternetHardDrivesFileDto> pageParam) {
        //获取对象
        InternetHardDrivesFileDto internetHardDrivesFileDto = pageParam.getSearchbean();
        //分页
        PageHelper.startPage(pageParam.getIndexPage(), pageParam.getPageSize());
        return internetHardDrivesFileMapper.internetHardDrivesFileSelectList(internetHardDrivesFileDto);
    }

    @Override
    public Boolean internetHardDrivesFileInsertList(InternetHardDrivesFileDto internetHardDrivesFileDto) {

        // 服务器地址
        String filePath = "D:\\\\weboa\\";
        Boolean bResult = true;

        InternetHardDrivesFile internetHardDrivesFile = new InternetHardDrivesFile();
        List<String> base64Datas = internetHardDrivesFileDto.getBase64Datas();
        Iterator<String> iterator = base64Datas.iterator();
        while (iterator.hasNext()) {
            String fileData = iterator.next();

            // 文件名
            String filename = "";
            // 文件类型
            String fileType = "";
            // 文件数据
            String data = "";
            String base64data = "";

            // 获取文件名称
            String[] a = fileData.split("data:", 2);
            if (a != null) {
                filename = a[0];
                base64data = a[1];
            }

            // 获取文件数据
            String[] b = base64data.split("base64,", 2);
            if (b != null) {
                data = b[1];
            }

            // 获取文件类型
            fileType = filename.substring(filename.lastIndexOf('.') + 1);

            internetHardDrivesFileDto.setIhdfName(filename);
            internetHardDrivesFileDto.setIhdfFiletype(fileType);

            // 获取当前系统时间
            String nowTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            internetHardDrivesFileDto.setIhdfTime(nowTime);

            String uploadTime = nowTime.replace("-", "").replace(":", "").replace(" ", "").concat("_");

            // 文件上传地址
            String destFilePath = filePath + uploadTime + filename;
            internetHardDrivesFileDto.setIhdfPath(destFilePath);
            // Base64字符串解码
            Base64.Decoder base64Decoder = Base64.getDecoder();
            try {
                byte[] d = base64Decoder.decode(data);
                for (int j = 0; j < d.length; j++) {
                    if (d[j] < 0) {
                        d[j] += 256;
                    }
                }

                OutputStream out = new FileOutputStream(destFilePath);
                out.write(d);
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
                throw new BizException("E00014", messageSource.getMessage("E00014", null, null));
            }

            BeanUtils.copyProperties(internetHardDrivesFileDto, internetHardDrivesFile);
            bResult = this.save(internetHardDrivesFile);
            if (!bResult) {
                throw new BizException("E00014", messageSource.getMessage("E00014", null, null));
            }

        }

        return bResult;
    }

    @Override
    public Boolean internetHardDrivesFileUpdateList(InternetHardDrivesFileDto internetHardDrivesFileDto) {
        // 是否存在相同的硬盘文件名
        boolean flg = noSameDepartName(internetHardDrivesFileDto);
        if(flg){
            InternetHardDrivesFile internetHardDrivesFile = new InternetHardDrivesFile();
            BeanUtils.copyProperties(internetHardDrivesFileDto,internetHardDrivesFile);
            return internetHardDrivesFileMapper.internetHardDrivesFileUpdateList(internetHardDrivesFile);
        }else{
            throw new BizException("E0007", messageSource.getMessage("E0007", null, null));
        }
    }

    @Override
    public Boolean internetHardDrivesFileDeleteList(InternetHardDrivesFileDto internetHardDrivesFileDto) {

        List<String> delGuids = new ArrayList<>();
        for (InternetHardDrivesFileSubDto subFile:internetHardDrivesFileDto.getIhdfDelGuids()) {
            delGuids.add(subFile.getIhdfGuid());
            File file = new File(subFile.getIhdfPath());
            if (file.exists()){
                file.delete();
            }

        }
        return internetHardDrivesFileMapper.internetHardDrivesFileDeleteList(delGuids);
    }

    @Override
    public List<InternetHardDrivesFileVo> internetHardDrivesFileSelectAll(PageParam<InternetHardDrivesFileDto> pageParam) {
        InternetHardDrivesFileDto internetHardDrivesFileDto = pageParam.getSearchbean();
        PageHelper.startPage(pageParam.getIndexPage(), pageParam.getPageSize());
        return internetHardDrivesFileMapper.internetHardDrivesFileSelectAll(internetHardDrivesFileDto);
    }

    @Override
    public InternetHardDrivesFileVo internetHardDrivesFileSelectDetail(InternetHardDrivesFileDto internetHardDrivesFileDto) {
        return internetHardDrivesFileMapper.internetHardDrivesFileSelectDetail(internetHardDrivesFileDto);
    }

    /**
     * 是否存在相同文件名称
     * @param internetHardDrivesFileDto 文件信息
     * @return 是否存在
     */
    private boolean noSameDepartName(InternetHardDrivesFileDto internetHardDrivesFileDto) {
        // 定义返回值
        boolean flg = false;

        QueryWrapper<InternetHardDrivesFile> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ihdf_name", internetHardDrivesFileDto.getIhdfName())
                    .ne("ihdf_guid", internetHardDrivesFileDto.getIhdfGuid())
                    .eq("ihd_guid", internetHardDrivesFileDto.getIhdGuid())
                    .eq("delflg", "1");
        if(this.count(queryWrapper) == 0){
            flg = true;
        }
        return flg;
    }
}
